package tools.promoter;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;

public class promoterUtils {

	public static void main(String[] args) throws Exception{

		if(args.length>0){
			if(args[0].equals("extractPattern")&&args.length>1){
				extractPattern(args[1]);
			}else if(args[0].equals("other")&&args.length==2){
					//other method
				}else{
				System.err.println(printHelp());
				System.exit(616);
			}
		}else{
			System.err.println(printHelp());
			System.exit(616);
		}
	}

	private static String printHelp(){
		String help="Usage: promoterUtils <cmd> <input>\n";
		help+="where <cmd> is:\n";
		help+="extractPattern - takes a tabseparated promoter file from fastaUtils findMotif (gene,motif,strand,start,stop) and prints the order of motifs for each gene. In this version, each distinct motif must have a separate name\n";
		help+="\t<input> = <promoter file>\n";
		
		return help;
	}
	
	private static void extractPattern(String promoterFile)throws Exception{
		ArrayList<Motif> curList= new ArrayList<Motif>();
		String curGene="";
		Motif motif;
		
		BufferedReader in= new BufferedReader(new FileReader(promoterFile));
		
		for(String s=in.readLine();s!=null;s=in.readLine()){
			final String[] l=s.split("\t");
			motif= new Motif(l[0],l[1],l[2].charAt(0),Integer.parseInt(l[3]),Integer.parseInt(l[4]));
			if(!curGene.equals(motif.getGene())){
				//print
				Collections.sort(curList);
				System.out.print(curGene+"\t");
				for (Motif m : curList) {
//					if(m.getStrand()=='+'){
//						System.out.print(m.getMotif().substring(0, 1).toUpperCase());
//					}else{
//						System.out.print(m.getMotif().substring(0, 1).toLowerCase());
//					}
					System.out.print(m.getMotif().substring(0, 1));
				}
				System.out.println();
				//reset
				curList= new ArrayList<Motif>();
				curGene=motif.getGene();
			}
			curList.add(motif);
		}
		//print last
		System.out.print(curGene+"\t");
		for (Motif m : curList) {
			if(m.getStrand()=='+'){
				System.out.print(m.getMotif().substring(0, 1).toUpperCase());
			}else{
				System.out.print(m.getMotif().substring(0, 1).toLowerCase());
			}
			System.out.print(m.getMotif().substring(0, 1));
		}
		System.out.println();
	}
}
